<?php


namespace app\zwt\controller;



use app\zwt\model\AdminModel;
use app\zwt\validate\AdminValidate;
use cmf\controller\AdminBaseController;

class AdminController extends AdminBaseController
{
    //页面显示
    public function index(){
        $keyword = input('keyword','');
        $where = [];
        if($keyword){
            $where[] = ['name', 'like', "%$keyword%"];
        }
        $list = AdminModel::order(['id'=>'DESC'])
            ->where($where)
            ->paginate(5);
        $this->assign('list',$list);
        return $this->fetch();
    }
    //添加页面显示
    public function add(){
        return $this->fetch();
    }
    //添加方法
    public function addPost()
    {
        $data = input('post.');

        //验证数据
        $validate = new AdminValidate();
        $res = $validate->scene('add')->check($data);
        if (!$res) {
            $this->error($validate->getError());
        }
        $image = $data['image'];
        $url = cmf_get_image_url($image);
        //入库
        if (AdminModel::create([
            'name' => $data['name'],
            'image' => $url,
            'mobile' => $data['mobile']
        ])) {
            $this->success('添加成功', 'admin/index');
        } else {
            $this->error('添加失败');
        }
    }
    //编辑
    public function edit()
    {
        $id = input('id');
        $list = AdminModel::find($id);
        return $this->fetch('edit', [
            'list' => $list
        ]);
    }

    public function editPost()
    {
        $data = input('post.');

        //验证器
        $validate = new AdminValidate();
        $result = $validate->scene('edit')->check($data);
        if (!$result) {
            $this->error($validate->getError());
        }
        //        查询用户是否存在
        $edit = AdminModel::find($data['id']);
        if(!$edit){
            $this->error('未查询到该数据');
        }

        $image = $data['image'];
        $url = cmf_get_image_url($image);
//        halt($url);
        $edit->name= $data['name'];
        $edit->mobile= $data['mobile'];
        $edit->image= $url;

        if ($edit->save()) {
            $this->success('修改成功','admin/index');
        } else {
            $this->error('修改失败');
        }
    }

    //单条删除
    public function delete()
    {
        $id = input('id/d');
        $del =AdminModel::destroy($id);
        //判断该id是否存在
        if (!$del) {
            $this->error('该数据不存在');
        }
        if ($del) {
            $this->success('删除成功', 'admin/index');
        } else {
            $this->error('删除失败');
        }
    }

    //排序
//    public function order()
//    {
//        $news = new AdminModel();
//        parent::listOrders($news);
//        $this->success('成功');
//    }
}